﻿using System.Management;
using System.Net.Security;
using System.Security;

namespace apitest.Application.Test.Services
{
    public class Test11Service:IDynamicApiController,IDisposable
    {
       
            private ManagementScope _managementScope;
            private bool _isConnected;

            /// <summary>
            /// 连接到远程计算机
            /// </summary>
            /// <param name="computerName">远程计算机名称或IP</param>
            /// <param name="username">用户名（格式：域名\用户名 或 计算机名\用户名）</param>
            /// <param name="password">密码</param>
            /// <returns>是否连接成功</returns>
            public bool Connect(string computerName, string username, string password)
            {
                try
                {
                    // 创建连接选项
                    var connectionOptions = new System.Management.ConnectionOptions
                    {
                        Username = username,
                        Password = password,
                        EnablePrivileges = true,
                        Impersonation = ImpersonationLevel.Impersonate,
                        Authentication = System.Management.AuthenticationLevel.PacketPrivacy
                    };

                    // 远程计算机WMI路径
                    string path = $"\\\\{computerName}\\root\\cimv2";
                    _managementScope = new ManagementScope(path, connectionOptions);

                    // 连接到远程WMI服务
                    _managementScope.Connect();
                    _isConnected = true;
                    Console.WriteLine($"成功连接到远程计算机: {computerName}");
                    return true;
                }
                catch (ManagementException ex)
                {
                    Console.WriteLine($"WMI连接错误: {ex.Message}");
                    return false;
                }
                catch (UnauthorizedAccessException ex)
                {
                    Console.WriteLine($"权限不足: {ex.Message}");
                    return false;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"连接失败: {ex.Message}");
                    return false;
                }
            }

            /// <summary>
            /// 在远程计算机上执行命令
            /// </summary>
            /// <param name="command">要执行的命令（如"ipconfig /all"）</param>
            /// <param name="output">命令输出结果</param>
            /// <returns>是否执行成功</returns>
            public bool ExecuteRemoteCommand(string command, out string output)
            {
                output = string.Empty;
                if (!_isConnected)
                {
                    output = "未连接到远程计算机，请先连接";
                    return false;
                }

                try
                {
                    // 创建进程启动信息
                    var processStartInfo = new ManagementClass(
                        _managementScope,
                        new ManagementPath("Win32_Process"),
                        new ObjectGetOptions());

                    // 设置进程参数
                    var inParams = processStartInfo.GetMethodParameters("Create");
                    inParams["CommandLine"] = command;

                    // 远程执行命令
                    var outParams = processStartInfo.InvokeMethod("Create", inParams, null);

                    // 获取进程ID
                    uint processId = (uint)outParams["processId"];
                    output = $"命令已在远程计算机执行，进程ID: {processId}";
                    return true;
                }
                catch (ManagementException ex)
                {
                    output = $"命令执行失败: {ex.Message}";
                    return false;
                }
                catch (Exception ex)
                {
                    output = $"执行命令时发生错误: {ex.Message}";
                    return false;
                }
            }

            /// <summary>
            /// 获取远程计算机的进程列表
            /// </summary>
            public void GetRemoteProcesses()
            {
                if (!_isConnected)
                {
                    Console.WriteLine("未连接到远程计算机，请先连接");
                    return;
                }

                try
                {
                    // 查询远程进程
                    var query = new ObjectQuery("SELECT Name, ProcessId FROM Win32_Process");
                    using (var searcher = new ManagementObjectSearcher(_managementScope, query))
                    {
                        Console.WriteLine("\n远程计算机进程列表:");
                        Console.WriteLine("--------------------------------");

                        foreach (var process in searcher.Get())
                        {
                            Console.WriteLine($"进程名: {process["Name"]}, PID: {process["ProcessId"]}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"获取进程列表失败: {ex.Message}");
                }
            }

        public void GetCpuUsage()
        {
            if (!_isConnected)
            {
                Console.WriteLine("未连接到远程计算机，请先连接");
                return;
            }

            var query = new ObjectQuery(
                   "SELECT PercentProcessorTime FROM Win32_PerfFormattedData_PerfOS_Processor  ");
            query = new ObjectQuery("SELECT * FROM Win32_BaseBoard");
            //Manufacturer  主板制造商
            //Product  型号
            //SerialNumber  序列号

            using (var searcher = new ManagementObjectSearcher(_managementScope, query))
            {
                // 获取查询结果
                foreach (var item in searcher.Get())
                {
                    // PercentProcessorTime就是CPU使用率（百分比）
                    if (item["PercentProcessorTime"] != null)
                    {
                        Console.WriteLine(     item["PercentProcessorTime"] );
                    }
                }
            }
        }

            /// <summary>
            /// 远程关闭计算机
            /// </summary>
            /// <param name="force">是否强制关闭</param>
            public bool ShutdownRemoteComputer(bool force = false)
            {
                if (!_isConnected)
                {
                    Console.WriteLine("未连接到远程计算机，请先连接");
                    return false;
                }

                try
                {
                    var managementClass = new ManagementClass(
                        _managementScope,
                        new ManagementPath("Win32_OperatingSystem"),
                        new ObjectGetOptions());

                    foreach (var managementObject in managementClass.GetInstances())
                    {
                        // 关闭计算机 (2 = 关闭, 4 = 重启, 1 = 注销)
                     //   managementObject.InvokeMethod("Win32Shutdown", new object[] { force ? 5 : 2 });
                    }

                    Console.WriteLine("已发送关闭命令到远程计算机");
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"关闭远程计算机失败: {ex.Message}");
                    return false;
                }
            }

            public void Dispose()
            {
              //  _managementScope?.Dispose();
                _isConnected = false;
            }

            // 示例用法
            public async Task T1()
            {
                // 远程计算机信息（请替换为实际信息）
                string remoteComputer = "192.168.220.132"; // 远程计算机IP或名称
                string username = "Administrator";       // 远程计算机用户名
                string password = "Ast.123456";        // 远程计算机密码

                using (var controller = new Test11Service())
                {
                    // 连接到远程计算机
                    if (!controller.Connect(remoteComputer, username, password))
                    {
                        Console.WriteLine("连接失败，程序退出");
                        return;
                    }

                    // 执行远程命令
                    if (controller.ExecuteRemoteCommand("ipconfig /all > C:\\remote_command_output.txt", out string result))
                    {
                        Console.WriteLine(result);
                    }
                    else
                    {
                        Console.WriteLine(result);
                    }

                    // 获取远程进程列表
                //    controller.GetRemoteProcesses();

                //获取CPU占用
                controller.GetCpuUsage();
                    // 远程关闭计算机（取消注释以启用）
                    // controller.ShutdownRemoteComputer(false);
                }

          
            }
        }

}
